package org.vergil.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import org.springframework.orm.jpa.LocalEntityManagerFactoryBean;
import org.vergil.config.dataConfig.DynamicDataSource;

import javax.jms.ConnectionFactory;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by vergil on 2/18/17.
 */

@Configuration
@ComponentScan("org.vergil")
@EnableAspectJAutoProxy//开启aop注解
@ImportResource(value = "classpath:beans.xml")
@PropertySource("classpath:/dev/db.properties")
public class SpringConfig {

    @Autowired
    Environment env;

    @Bean
    public DynamicDataSource dataSource(){
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put("devDataSource", devDataSource());
        dataSourceMap.put("testDataSource", testDataSource());
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        dynamicDataSource.setDefaultTargetDataSource(devDataSource());
        return dynamicDataSource;
    }

    @Bean
    public DataSource devDataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("db.driver"));
        dataSource.setUrl(env.getProperty("db.url"));
        dataSource.setUsername(env.getProperty("db.username"));
        dataSource.setPassword(env.getProperty("db.password"));
        return dataSource;
    }

    @Bean
    public DataSource testDataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("test.driver"));
        dataSource.setUrl(env.getProperty("test.url"));
        dataSource.setUsername(env.getProperty("test.username"));
        dataSource.setPassword(env.getProperty("test.password"));
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(DynamicDataSource dataSource){
        return new JdbcTemplate(dataSource);
    }

    @Bean
    public NamedParameterJdbcTemplate namedParameterJdbcTemplate(DynamicDataSource dataSource){
        return new NamedParameterJdbcTemplate(dataSource);
    }

}
